<template>
  <div v-loading="loading" class="rc-cont">
    <div v-if="!isSeas" class="rc-head">
      <template v-if="teamEditAuth">
        <el-button
          v-if="list.length === 0"
          icon="el-icon-plus"
          @click="handleClick('add')">
          {{ $t('crm.components.e77f8cb380a20f4140c31d83f519c329') }}
        </el-button>
        <el-button v-if="list.length > 0" @click="handleClick('edit')">
          {{ $t('crm.components.40c6bba2f647d2ed54c565fbd0e28d30') }}
        </el-button>
        <el-button v-if="list.length > 0" @click="handleClick('delete')">
          {{ $t('crm.components.00b658898ae0826c9a98e995ba9d0f46') }}
        </el-button>
      </template>
    </div>
    <el-table
      :data="list"
      :height="tableHeight"
      :span-method="objectSpanMethod"
      stripe>
      <el-table-column
        v-for="(item, index) in fieldList"
        :key="index"
        :prop="item.prop"
        :label="item.label"
        :min-width="item.width"
        show-overflow-tooltip>
        <template slot-scope="scope">
          <span v-if="item.prop=='userName'">
            <wx-open-data :openid="scope.row[item.prop]" />
          </span>
          <span v-else>
            {{ fieldFormatter(scope.row, scope.column) }}
          </span>
        </template>
      </el-table-column>
    </el-table>

    <!-- 销售产品添加 -->
    <cross-sell-products-add
      v-if="updateDialogShow"
      :id="id"
      :user-list="userList"
      :crm-type="crmType"
      :edit-list="editList"
      :visible.sync="updateDialogShow"
      @success="getDetail" />
  </div>
</template>

<script type="text/javascript">
import {
  crmCustomerQueryTeamProductAPI,
  crmCustomerDeleteTeamProductAPI
} from '@/api/crm/customer'
import {
  crmBusinessQueryTeamProductAPI,
  crmBusinessDeleteTeamProductAPI
} from '@/api/crm/business'
import {
  crmContractQueryTeamProductAPI,
  crmContractDeleteTeamProductAPI
} from '@/api/crm/contract'
import {
  crmContactsQueryTeamProductAPI,
  crmContactsDeleteTeamProductAPI
} from '@/api/crm/contacts'
import {
  crmReceivablesQueryTeamProductAPI,
  crmReceivablesDeleteTeamProductAPI
} from '@/api/crm/receivables'
import {
  crmReturnVisitQueryTeamProductAPI,
  crmReturnVisitDeleteTeamProductAPI
} from '@/api/crm/visit'

import CrossSellProductsAdd from './CrossSellProductsAdd'

import { mapGetters } from 'vuex'
import { getPermissionByKey } from '@/utils'
import { objDeepCopy } from '@/utils'
import { separator } from '@/filters/vueNumeralFilter/filters'

export default {
  // CrossSellProducts 交叉销售产品
  name: 'CrossSellProducts',
  components: {
    CrossSellProductsAdd
  },
  mixins: [],
  inject: ['rootTabs'],
  props: {
    // 模块ID
    id: [String, Number],
    // 联系人人下 新建商机 需要联系人里的客户信息  合同下需要客户和商机信息
    detail: {
      type: Object,
      default: () => {
        return {}
      }
    },
    // 没有值就是全部类型 有值就是当个类型
    crmType: {
      type: String,
      default: ''
    },
    // 是公海 默认是客户
    isSeas: {
      type: Boolean,
      default: false
    },
    userList: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      loading: false,
      list: [],
      fieldList: [
        { prop: 'productName', width: '100', label: this.$t('crm.components.8398651dcf56920e55b0ec5420f527ac') },
        { prop: 'productCategoryName', width: '100', label: this.$t('crm.components.225e12d5100478d6929461550894f336') },
        { prop: 'price', width: '120', label: this.$t('crm.components.d521f53589c1c6488ab8ce468f7a901c') + `(${this.$unit('crm')})` },
        { prop: 'desc', width: '120', label: '分成依据类型' },
        { prop: 'descRate', width: '120', label: '分成依据比例' },
        { prop: 'userName', width: '120', label: '分成人员' },
        { prop: 'rate', width: '120', label: '分成比例' }
      ],

      tableHeight: '400px',
      editList: [],
      updateDialogShow: false // 添加编辑
    }
  },
  computed: {
    ...mapGetters(['crm']),
    teamEditAuth() {
      return !!getPermissionByKey(`crm.${this.crmType}.teamsave`)
    },
    // 团队人员ids
    userListIds() {
      return this.userList.map(item => item.userId)
    }
  },
  watch: {
    id(val) {
      this.list = []
      this.getDetail()
    },

    'rootTabs.currentName'(val) {
      if (val === 'RelativeTeam') {
        this.getDetail(false)
      }
    },

    userList() {
      // 团队人员发送变化，刷新列表
      this.getDetail()
    }
  },
  mounted() {
    this.getDetail()
  },
  methods: {
    /**
     * @description: 获取信息
     * @param {*} loading
     * @return {*}
     */
    getDetail(loading = true) {
      this.loading = loading
      const request = {
        customer: crmCustomerQueryTeamProductAPI,
        business: crmBusinessQueryTeamProductAPI,
        contract: crmContractQueryTeamProductAPI,
        contacts: crmContactsQueryTeamProductAPI,
        receivables: crmReceivablesQueryTeamProductAPI,
        visit: crmReturnVisitQueryTeamProductAPI
      }[this.crmType]
      request(this.id)
        .then(res => {
          this.loading = false
          const list = res.data
          list.forEach(item => {
            if (!this.userListIds.includes(item.userId)) {
              delete item.userId
            }
          })
          this.list = list

          this.handleItemTableSpan()
        })
        .catch(() => {
          this.loading = false
        })
    },

    /**
     * @description: 标记数据中的合并信息
     * @return {*}
     */
    handleItemTableSpan() {
      // 分成依据类型单元格合并
      let desc = ''
      const descSpanObj = {}
      let descSpanIndex = 1
      // 产品分类单元格合并
      const spanObj = {}
      let productId = ''
      let spanIndex = 1
      this.list.forEach((item, index) => {
        if (item.productId !== productId) {
          productId = item.productId
          spanIndex = index
          spanObj[spanIndex] = 1
          desc = item.desc
          descSpanIndex = index
          descSpanObj[descSpanIndex] = 1
        } else {
          if (item.desc == desc) {
            descSpanObj[descSpanIndex]++
          } else {
            descSpanIndex = index
            descSpanObj[descSpanIndex] = 1
            desc = item.desc
          }
          spanObj[spanIndex]++
        }
      })

      let preItem = null
      let descPreItem = null

      this.list.forEach((item, index) => {
        const span = spanObj[index]
        const descSpan = descSpanObj[index]
        item.index = index
        if (span !== undefined) {
          item.rowspan = span
          item.colspan = 1
          item.start = index
          item.end = index + span
          preItem = item
        } else {
          item.rowspan = 0
          item.colspan = 0
          if (preItem) {
            item.start = preItem.start
            item.end = preItem.end
          }
        }

        if (descSpan !== undefined) {
          item.descRowspan = descSpan
          item.descColspan = 1
          item.descStart = index
          item.descEnd = index + descSpan
          descPreItem = item
        } else {
          item.descRowspan = 0
          item.descColspan = 0
          if (descPreItem) {
            item.descStart = descPreItem.descStart
            item.descEnd = descPreItem.descEnd
          }
        }
      })
    },

    /**
     * @description: 合并单元格
     * @param {*} row
     * @param {*} column
     * @param {*} rowIndex
     * @param {*} columnIndex
     * @return {*}
     */
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex <= 2) {
        if (rowIndex % 2 === 0) {
          return row
        } else {
          return row
        }
      } else if ([3, 4].includes(columnIndex)) {
        return {
          rowspan: row.descRowspan,
          colspan: row.descColspan
        }
        // if (rowIndex <= 1) {
        //   return {
        //     rowspan: 1,
        //     colspan: 1
        //   }
        // } else if (rowIndex == 2) {
        //   return {
        //     rowspan: 2,
        //     colspan: 1
        //   }
        // } else {
        //   return {
        //     rowspan: 0,
        //     colspan: 0
        //   }
        // }
      }
    },

    /**
     * @description: 格式化内容
     * @param {*} row
     * @param {*} column
     * @return {*}
     */
    fieldFormatter(row, column) {
      if (['rate', 'descRate'].includes(column.property)) {
        return `${row[column.property]}%`
      } else if (column.property === 'userName') {
        return `${row[column.property]}${row.userId ? '' : this.$t('crm.components.579bf2808036f46316dfdceab3d11a8a')}`
      } else if (column.property == 'price') {
        return separator(this.$money('crm', row[column.property] || 0))
      }
      return row[column.property] === '' || row[column.property] === null ? '--' : row[column.property]
    },

    /**
     * @description: 头部操作
     * @param {*} type
     * @return {*}
     */
    handleClick(type) {
      if (type == 'add') {
        // 添加
        this.editList = null
        this.updateDialogShow = true
      } else if (type == 'edit') {
        this.editList = objDeepCopy(this.list)
        this.updateDialogShow = true
      } else if (type == 'delete') {
        const removeRequest = {
          customer: crmCustomerDeleteTeamProductAPI,
          contract: crmContractDeleteTeamProductAPI,
          business: crmBusinessDeleteTeamProductAPI,
          contacts: crmContactsDeleteTeamProductAPI,
          receivables: crmReceivablesDeleteTeamProductAPI,
          visit: crmReturnVisitDeleteTeamProductAPI
        }[this.crmType]
        this.$confirm(
          this.$t('crm.components.58034eb811d924cfc35c4fd37ef8f9f4'),
          this.$t('crm.components.e40a1301ec52caa9b77b8b66509c928e'),
          {
            confirmButtonText: this.$t('crm.components.73e946acf98816ca100b5da78e6535bb'),
            cancelButtonText: this.$t('crm.components.6b39f545caeaf91d0e36c260b999fafe'),
            type: 'warning'
          }
        )
          .then(() => {
            this.loading = true
            removeRequest(this.id)
              .then(res => {
                this.$message({
                  type: 'success',
                  message: this.$t('crm.components.f9debbb85d558afd80b1900df21b4dde')
                })
                this.loading = false
                this.getDetail()
              })
              .catch(() => {
                this.loading = false
              })
          })
          .catch(() => {})
      }
    },

    /**
     * 添加操作
     */
    handleCallBack(data) {
      this.$bus.emit('crm-tab-num-update')
      this.getDetail()
    }
  }
}
</script>

<style lang="scss" scoped>
@import "../../styles/relativecrm.scss";

.handle-item {
  position: relative;
  padding-bottom: 15px;

  .handle-item-name {
    flex-shrink: 0;
    width: 90px;
  }

  .handle-item-content {
    flex: 1;
  }
}
</style>
